package com.glodon.paas.search.util;

import java.io.InputStream;

import javax.ws.rs.core.MediaType;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.glodon.paas.databag.api.bean.DatabagDto;
import com.glodon.paas.exception.PaasServerExceptionFactory;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

/**
 * 负责databag的调用服务.
 * 
 * @author botao.liao
 * 
 */
@Component
public class DatabagWebService extends AbstractWebService {
    @Value("${api.internal.databag.url}")
    private String databagInternalUrl;

    /**
     * 获取数据包的manifest文件.
     * 
     * @param databagId
     * @return
     */
    public String getManifest(String databagId) {
        StringBuffer url = new StringBuffer(databagInternalUrl.trim());
        url.append("/").append(databagId).append("/path/manifest.json");
        WebResource resource = Client.create(clientConfig).resource(url.toString());
        ClientResponse c = resource.type(MediaType.APPLICATION_JSON_TYPE).get(ClientResponse.class);
        if (c.getStatus() != 200) {
            throw PaasServerExceptionFactory.internalAPIException("getting " + databagId + " manifest.json failed. "
                    + c.getEntity(String.class), null);
        }
        String manifest = c.getEntity(String.class);
        return manifest;
    }

    /**
     * 下载数据包里的可索引资源.
     * 
     * @param databagId
     * @param resource
     * @return
     */
    public InputStream downloadResource(String databagId, String resource) {
        StringBuffer url = new StringBuffer(databagInternalUrl.trim());
        url.append("/").append(databagId).append("/path/").append(resource.trim());
        WebResource r = Client.create(clientConfig).resource(url.toString());
        ClientResponse resp = r.get(ClientResponse.class);
        if (resp.getStatus() != 200) {
            throw PaasServerExceptionFactory
                    .internalAPIException("failed to download resource " + url.toString(), null);
        }
        InputStream inputStream = resp.getEntityInputStream();
        return inputStream;
    }

    /**
     * 获取databag的meta对象
     * 
     * @param databagId
     * @return
     */
    public DatabagDto getDatabag(String databagId) {
        WebResource resource = Client.create(clientConfig).resource(databagInternalUrl.trim() + "/" + databagId);
        DatabagDto databagDto = resource.get(DatabagDto.class);
        return databagDto;
    }

    public void setDatabagInternalUrl(String databagInternalUrl) {
        this.databagInternalUrl = databagInternalUrl;
    }

}
